package cn.com.pansky.action.myaccount;

import java.io.File;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;

import cn.com.pansky.action.imgContrast.ImgContrast;
import cn.com.pansky.action.logs.Log;
import cn.com.pansky.service.CommonService;
import cn.com.pansky.util.CardNumUtil;
import cn.com.pansky.util.CommonUtils;
import cn.com.pansky.util.DateUtil;
import cn.com.pansky.util.EncryptionUtils;
import cn.com.pansky.util.LssConstant;
import net.vsame.url2sql.action.CommonAction;
import net.vsame.url2sql.helper.SqlHelper;
import net.vsame.url2sql.sql.Model;
/**
 * 用户注册
 * @author Administrator
 *
 */
public class UserAction extends CommonAction {
	private Log log = new Log();
	CommonService cs = new CommonService();
	/**
	 * 获取验证码
	 * @throws Exception 
	 */
	public void checkPhoneNum() throws Exception{
		String AA032 = getParam("AA032");
		if(CardNumUtil.phoneNumber(AA032)){
			String sql = urlConfig.getVar("queryByPhoneNum");
			// 根据身份证获取用户信息
			Model m = SqlHelper.queryOne(sql, AA032);
			if(m != null) {
				datas.put("isPass", false);
				datas.put("info", "该手机号已注册，请直接登陆");
				context.getDatas().put("result", datas);
			}else{
				
				JSONObject obj = cs.aliyunSms(AA032);
				if (!"0".equals(obj.getString("code"))) {
					JSONObject json = new JSONObject();
					json.put("isPass", false);
					json.put("info", obj.getString("msg"));
					context.getDatas().put("result", json);
					return;
				}
				String code = obj.getString("content");
				context.getServletSession().setAttribute("AA032", AA032);
				context.getServletSession().setAttribute("AF016", code);
				JSONObject json = new JSONObject();
				json.put("isPass", true);
				json.put("info", "验证码发送成功");
				context.getDatas().put("result", json);
			}
		} else {
			datas.put("isPass", false);
			datas.put("info", "请输入正确的手机号");
			context.getDatas().put("result", datas);
		}
	}
	
	public void checkCode() {
		if (null != context.getServletSession().getAttribute("AA032") && null != context.getServletSession().getAttribute("AF016")) {
			if (!context.getServletSession().getAttribute("AA032").equals(getParam("AA032"))) {
				datas.put("isPass", false);
				datas.put("info", "请输入接收短信的手机号！");
				context.getDatas().put("result", datas);
				return;
			}
			Model m = SqlHelper.queryOne("select * from (select * from CA20 where AA032 = ? and AF016 = ? order by AF014 desc) where rownum = 1", 
					context.getSessionVal("AA032"),getParam("AF016"));
			//当前时间
			long nowTime = new Timestamp(System.currentTimeMillis()).getTime();
			if (m != null) {
				//验证码发送时间
				long AF017 = m.getLong("AF017");
				double time = (nowTime - AF017)/1000/60;
				if (time>5) {
					datas.put("isPass", false);
					datas.put("info", "验证码超时");
				}else{
					context.getServletSession().removeAttribute("AF016");
					datas.put("isPass", true);
					datas.put("info", "验证码校验成功！");
				}
			} else {
				datas.put("isPass", false);
				datas.put("info", "验证码输入错误");
			}
		} else {			
			datas.put("isPass", false);
			datas.put("info", "验证码已失效，请重新获取");
		}
		context.getDatas().put("result", datas);
	}

	/**
	 * 校验验证码
	 * 
	 * @throws Exception
	 */
	public void validateCode(){
		if (null != context.getServletSession().getAttribute("AA032") && null != context.getServletSession().getAttribute("AF016")) {
			Model m = SqlHelper.queryOne("select * from (select * from CA20 where AA032 = ? and AF016 = ? order by AF014 desc) where rownum = 1", 
					context.getSessionVal("AA032"),getParam("AF016"));
			//当前时间
			long nowTime = new Timestamp(System.currentTimeMillis()).getTime();
			if (m != null) {
				//验证码发送时间
				long AF017 = m.getLong("AF017");
				double time = (nowTime - AF017)/1000/60;
				if (time>5) {
					datas.put("isPass", false);
					datas.put("info", "验证码超时");
				}else{
					context.getServletSession().removeAttribute("AF016");
//		if (null != context.getServletSession().getAttribute("AA032") || "".equals(context.getServletSession().getAttribute("AA032"))) {
					saveUser();
//		} else {
//			datas.put("isPass", true);
//			datas.put("info", "注册保存失败，请重新注册！");
//			context.getDatas().put("result", datas);
//		}
					return;
				}
			} else {
				datas.put("isPass", false);
				datas.put("info", "验证码输入错误");
			}
		} else {			
			datas.put("isPass", false);
			datas.put("info", "验证码已失效，请重新获取");
		}
		context.getDatas().put("result", datas);
	}	
	/**
	 * 保存用户注册信息
	 */
	public void saveUser(){
		String image_best = context.getParam("image_best");
		if (null!=image_best || !"".equals(image_best)) {
			datas.put("isPass", false);
			datas.put("info", "请下载新版本！");
			context.getDatas().put("result", datas);
		}
		
		//日志记录start
		String AF001 = log.start("ZC");
		
		// 姓名
		String name = getParam("CA003");
		// 身份证号
		String cardId = getParam("CA006");
		
		String CA001 = "";
		String AA001 = "";
		
		if(CommonUtils.isIdentityId(cardId)){
			cardId = CardNumUtil.cardNum(cardId);
			// 根据姓名，身份证号判断该信息是否存在，如果存在直接引用，否则保存
			String sql = urlConfig.getVar("queryRC03ByName");
			Model model = SqlHelper.queryOne(sql, cardId, name);
			String ca001 = ""; // 服务对象ID
			if(model != null) {
				// 如果信息存在，账户表直接引用
				ca001 = model.getString("CA001"); // 取得服务对象ID
			} else {
				// 保存用户基本信息
				SqlHelper.execute("saveRC03", name, cardId);
				sql = urlConfig.getVar("queryRC03ByName");
				ca001 = SqlHelper.queryOne(sql, cardId, name).getString("CA001");
			}
			String aa001 = UUID.randomUUID().toString();
			CA001 = ca001;
			// 保存账户信息
			String phoneNum = (String) context.getSessionVal("AA032");// 获取手机号
			String sqlsave = urlConfig.getVar("saveRC10"); // 获取sql
			SqlHelper.execute(sqlsave,aa001, ca001, phoneNum, phoneNum, DateUtil.current19Time());
			// 根据手机号获取用户ID
//			sql = urlConfig.getVar("queryRC10ByAA032");
//			String aa001 = SqlHelper.queryOne(sql, phoneNum).getString("AA001");
			// 密码
			String pass = EncryptionUtils.md5(getParam("AA002"));
			String sql1 = urlConfig.getVar("saveRA02"); // 获取sql
			SqlHelper.execute(sql1, aa001, pass);
			
			String updCA002 = urlConfig.getVar("updCA002");
			SqlHelper.execute(updCA002, ca001);
			
			AA001 = aa001;
			context.getServletSession().removeAttribute("AA032");
			datas.put("isPass", true);
			datas.put("info", "注册成功");
			
		} else {
			datas.put("isPass", false);
			datas.put("info", "您输入的身份证号码有误，请您核对");
		}
		
		//日志记录end
		boolean result = log.end(AF001, datas.get("isPass"), datas.get("info"), CA001, AA001);
		System.out.println("日志：个人版新用户注册："+result);

		context.getDatas().put("result", datas);
	}
	

/**
	 * 刷脸 扫描身份证zgss
	 * 保存用户注册信息
	 */
	public void saveUserInfo(){
		
		//日志记录start
		String AF001 = log.start("ZC");
		
		// 姓名
		String name = getParam("CA003");
		// 身份证号
		String cardId = getParam("CA006");
		
		
		String phoneNum = (String) context.getSessionVal("AA032");// 获取手机号
//		phoneNum = "15109203842";
		JSONObject json = new JSONObject();				
		//实名认证
		String imgPath = getParam("img"); // 身份证图片
		// 获取刷脸图片
		String image_best = getParam("image_best");
		String image_env = getParam("image_env");
		String delta = getParam("delta");
		File file = new File(imgPath);// 身份证上传后的临时文件
		File file2 = new File(image_best);// 刷脸上传后的临时文件
		if (!file.exists() || !file2.exists()) {
			json.put("isPass", false); // 认证失败
			json.put("info", "获取身份证或脸部照片失败，请重新扫描！"); // 认证失败
			context.getDatas().put("result", json);
			return;
		}
		JSONObject jsons = new JSONObject();
		try {
			jsons = cs.idendetify(file.getPath());
		} catch (KeyManagementException e) {
			json.put("isPass", false); // 认证失败
			json.put("info", "识别身份证信息失败，请重新扫描身份证！"); // 认证失败
			context.getDatas().put("result", json);
			return;
		} catch (NoSuchAlgorithmException e) {
			json.put("isPass", false); // 认证失败
			json.put("info", "识别身份证信息失败，请重新扫描身份证！"); // 认证失败
			context.getDatas().put("result", json);
			return;
		} catch (IOException e) {
			json.put("isPass", false); // 认证失败
			json.put("info", "识别身份证信息失败，请重新扫描身份证！"); // 认证失败
			context.getDatas().put("result", json);
			return;
		}
		String CA001 = "";
		String AA001 = "";
		
		if(CommonUtils.isIdentityId(cardId)){
			if (name.equals(jsons.getString("CA003"))
			&& cardId.equals(jsons.getString("CA006")) ) {
			
			cardId = CardNumUtil.cardNum(cardId);
					
			//比对身份证和刷脸照片
			JSONObject result = ImgContrast.imgCompare(imgPath, image_best, image_env, delta);
			if(0 != result.getIntValue("code")){
				json.put("isPass", false);
				json.put("info", "请确认身份证与刷脸是同一人！");
				context.getDatas().put("result", json);
			}else{
				
				double num = result.getDoubleValue("confidence");
				// 判断照片相似度
				if (num  > LssConstant.CONFIDENCE) {
					String id = "";
				
					try {
						cs.isnertRC06(image_best, CA001, num, id);
					} catch (Exception e) {
						json.put("isPass", false); // 认证失败
						json.put("info", "保存脸部特征失败，请重新操作！"); // 认证失败
						context.getDatas().put("result", json);
						return;
					}
					file2.delete();
				} else {
					json.put("isPass", false);
					json.put("info", "请确认身份证与刷脸是同一人！");
					context.getDatas().put("result", json);
					file.delete();
					file2.delete();
					//日志记录end
					boolean result1 = log.end(AF001, json.getString("isPass"), json.getString("info"));
					return;
				}
			}		
				
			// 根据姓名，身份证号判断该信息是否存在，如果存在直接引用，否则保存
			String sql = urlConfig.getVar("queryRC03ByName");
			Model model = SqlHelper.queryOne(sql, cardId, name);
			String ca001 = ""; // 服务对象ID
			if(model != null) {
				// 如果信息存在，账户表直接引用
				ca001 = model.getString("CA001"); // 取得服务对象ID
			} else {
				// 保存用户基本信息
				SqlHelper.execute("saveRC03", name, cardId);
				sql = urlConfig.getVar("queryRC03ByName");
				ca001 = SqlHelper.queryOne(sql, cardId, name).getString("CA001");
			}
			CA001 = ca001;
			String aa001 = UUID.randomUUID().toString();
					
			// 如果认证成功，则将民族，性别，出生年月，图片更新至用户信息中
			String sql0 = urlConfig.getVar("saveRC03Info");
			SqlHelper.execute(sql0, jsons.getString("CA009"),
					cs.getValueByName("AAC005", jsons.getString("CA051")),
					cs.getAac004(jsons.getString("CA050")),
					jsons.getString("CA052"), CA001);

			String id = "";
			//新增该条信息
			try {
				cs.isnertRC05(CA001, imgPath, id);
			} catch (Exception e) {
				json.put("isPass", false); // 认证失败
				json.put("info", "保存身份证照片失败，请重新操作！"); // 认证失败
				context.getDatas().put("result", json);
				return;
			}
			file.delete(); // 删除身份证图片临时文件

			
			// 保存账户信息
			String sqlsave = urlConfig.getVar("saveRC10"); // 获取sql
			SqlHelper.execute(sqlsave,aa001, ca001, phoneNum, phoneNum, DateUtil.current19Time());
			// 密码
			String pass = EncryptionUtils.md5(getParam("AA002"));
			String sql1 = urlConfig.getVar("saveRA02"); // 获取sql
			SqlHelper.execute(sql1, aa001, pass);		
			
			String updCA002 = urlConfig.getVar("updCA002");
			SqlHelper.execute(updCA002, ca001);
			
			AA001 = aa001;
			context.getServletSession().removeAttribute("AA032");
			datas.put("isPass", true);
			datas.put("info", "注册成功");
		
		    } else {
			datas.put("isPass", false); // 认证失败
			datas.put("info", "身份证姓名与注册时填写信息不一致！"); 
			
		    } 													
			} else {
					datas.put("isPass", false);
					datas.put("info", "您输入的身份证号码有误，请您核对");				
			}
			
	
		//日志记录end
		boolean result = log.end(AF001, datas.get("isPass"), datas.get("info"), CA001, AA001);
		System.out.println("日志：个人版新用户注册："+result);
		
		context.getDatas().put("result", datas);
	}
	
	
	
	/**
	 * 用户注销登陆
	 */
	public void exit(){
		context.getServletSession().removeAttribute("user");
	}
	
	/**
	 * 修改用户姓名
	 */
	public void updUser() {
		//日志记录start
		String AF001 = log.start(" ", "UN");
		
		Model user = (Model)context.getSessionVal("user");
		String aa001 = user.getString("AA001"); // 获取用户ID
		String sql1 = "select AA111 from RC10 where AA001 = ?"; 
		Model m = SqlHelper.queryOne(sql1, aa001);
		if (m.getString("AA111").equals("1")) {
			datas.put("isPass",false);
			datas.put("info","您已实名认证，不可修改信息！");
			context.getDatas().put("result", datas);
			//日志记录end
			boolean result = log.end(AF001, datas.get("isPass"), datas.get("info"));
			System.out.println("日志：修改姓名和身份证号"+result);
			return;
		}
		String sql = urlConfig.getVar("queryCA001ByRC10");
		// 根据用户ID查询RC03表CA001
		Model model = SqlHelper.queryOne(sql, aa001);
		String ca001 = model.getString("CA001");
		// 拼接修改用户sql
		StringBuffer strBuffer = new StringBuffer("update rc03 set ");
		String val = context.getParam("CA003");
		if(val != null && !val.equals("")) {
			// 姓名不为空，修改姓名
			strBuffer.append(" CA003=? where CA001=?");
		}
		if(context.getParam("CA006") != null && !context.getParam("CA006").equals("")) {
			if (!CommonUtils.isIdentityId(context.getParam("CA006"))) {
				datas.put("isPass",false);
				datas.put("info","请输入正确的身份证号！");
				context.getDatas().put("result", datas);
				//日志记录end
				boolean result = log.end(AF001, datas.get("isPass"), datas.get("info"));
				System.out.println("日志：修改姓名和身份证号"+result);
				return;
			}
			String sql_ = "SELECT * FROM RC03 WHERE CA006 = ?";
			Model m_  = SqlHelper.queryOne(sql_, getParam("CA006"));
			if (null != m_) {
				datas.put("isPass", false);
				datas.put("info", "该身份证号已存在，不允许重复！");
				context.getDatas().put("result", datas);
				return;
			}
			// 身份证号不为空，修改身份证号
			strBuffer.append(" CA006=? where CA001=?");
			val = CardNumUtil.cardNum(context.getParam("CA006"));
		}
		// 执行db操作
		int i = SqlHelper.execute(strBuffer.toString(), val, ca001);
		datas.put("isPass", i==1?true:false);
		//日志记录end
		boolean result = log.end(AF001, datas.get("isPass"), datas.get("info"));
		System.out.println("日志：修改姓名和身份证号"+result);

		context.getDatas().put("result", datas);
	}
}
